package com.xiaocikuai.smallchunks.utils;

import com.xiaocikuai.smallchunks.entity.User.UserOnline;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Component
public class SessionListener implements HttpSessionListener {

    private  Map<String, UserOnline> onlineUsers = new ConcurrentHashMap<>();

    // 添加用户到在线列表
    public void addUserOnline(String username, String device) {
        UserOnline userOnline = new UserOnline(username, device);
        onlineUsers.put(username, userOnline);
    }

    private void removeUserOnline(String username) {
        onlineUsers.remove(username);
    }

    // 获取在线用户列表
    public List<UserOnline> getOnlineUsers() {
        return new ArrayList<>(onlineUsers.values());
    }

    // HttpSessionListener 接口的方法，处理会话创建事件
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        // 这里可以添加处理逻辑，例如记录会话创建时间等
        System.out.println("Session Created: " + se.getSession().getId());
    }

    // HttpSessionListener 接口的方法，处理会话销毁事件
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        String username = (String) se.getSession().getAttribute("username");
        if (username != null) {
            onlineUsers.remove(username);
        }
    }

    // 检查并移除不活跃的用户
    public void checkAndRemoveInactiveUsers() {
        long currentTime = System.currentTimeMillis();
        List<String> inactiveUsers = onlineUsers.values().stream()
                .filter(userOnline -> currentTime - userOnline.getLastActiveTimeAsTimestamp() > 60000) // 超过一分钟没有活动的用户
                .map(UserOnline::getUsername)
                .collect(Collectors.toList());
        inactiveUsers.forEach(this::removeUserOnline);
    }
}
